package com.borya.service.mobile.impl;

import com.alibaba.fastjson.JSONObject;
import com.borya.constant.RedisConstant;
import com.borya.constant.SystemConstant;
import com.borya.dao.*;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.db.*;
import com.borya.model.entity.*;
import com.borya.model.enumcation.OtherConfType;
import com.borya.service.impl.BaseServiceImpl;
import com.borya.service.mobile.SdkUserService;
import com.borya.statuscode.StatusCode;
import com.borya.task.AutomaticAudittask;
import com.borya.task.model.RespInfo;
import com.borya.util.Constant;
import com.borya.util.DateUtils;
import com.borya.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component("sdkUserServiceImpl")
public class SdkUserServiceImpl extends BaseServiceImpl implements SdkUserService {

    public Logger log = Logger.getLogger(getClass());

    @Autowired("sdkUserDAO")
    private SdkUserDAO sdkUserDAO;

    @Autowired("registOrderInfoDAO")
    private RegistOrderInfoDAO registOrderInfoDAO;

    @Autowired("userDAOImpl")
    private UserDAO userDAO;

    @Autowired("merchantDAO")
    private MerchantDAO merchantDAO;

    @Autowired("blackIdCardDAO")
    private BlackIdCardDAO blackIdCardDAO;

    @Autowired("appConfDAOImpl")
    private AppConfDAO appConfDAO;

    @Autowired("webUserDAOImpl")
    private WebUserDAO webUserDAO;

    @Autowired("merchantFillServiceDAO")
    private MerchantFillServiceDAO merchantFillServiceDAO;

    @Override
    public String saveMerchantActivation(JSONObject json, UserToken userToken, HeaderEntity authHeader) {
        String sdkUserId = authHeader.getUserId(); // 单点结算userId
        final String lockKey = "selfregist" + sdkUserId;
        boolean lock = userDAO.redis_setNx(lockKey, "1");
        if (!lock) {
            return StatusCode.PARAM_ERROR.json().msg("请求过快").toString();
        }

        try {
            sdkUserDAO.redis_expire(lockKey, 600);
            String appId = userToken.getAppId(); // sdk 下家appid
            String phone = json.getString("userPhone");
            String identityCard = json.getString("identityCard"); // 企业和个人都是身份证号码
            String identityCardName = json.getString("identityCardName");
            String identityCardAddress = json.getString("identityCardAddress");
            String period = json.getString("period");
            String merchantType = json.getString("merchantType");
            String identifyPhotoHand = json.getString("identifyPhotoHand");
            String identifyPhotoHead = json.getString("identifyPhotoHead");
            String identifyPhotoFront = json.getString("identifyPhotoFront");
            String identifyPhotoReverse = json.getString("identifyPhotoReverse");
            String shopAddress = json.getString("shopAddress");
            String shopSpecificAddress = json.getString("shopSpecificAddress");
            String cityName = json.getString("cityName");
            String cityCode = json.getString("cityCode");
            String signPicture = json.getString("signPicture");
            String companyName = json.getString("companyName");
            String businessLicence = json.getString("businessLicence"); // 营业执照编号，个人用户不用传
            String doorPictureLeft = json.getString("doorPictureLeft");
            String doorPictureRight = json.getString("doorPictureRight");
            String handPicture = json.getString("handPicture");
            String kMRecordCode = json.getString("deviceCode");
            String devMacAddress = "";
            if (json.containsKey("devMac")) {
                devMacAddress = json.getString("devMac");
            }

            MerchantActivateParamsInfo info = new MerchantActivateParamsInfo();
            info.setIdentityCard(identityCard);
            info.setIdentityCardName(identityCardName);
            info.setIdentityCardAddress(identityCardAddress);
            info.setPeriod(period);
            info.setIdentifyPhotoHead(identifyPhotoHead);
            info.setIdentifyPhotoFront(identifyPhotoFront);
            info.setIdentifyPhotoReverse(identifyPhotoReverse);
            info.setIdentifyPhotoHand(identifyPhotoHand);
            info.setMerchantType(merchantType);
            info.setShopAddress(shopAddress);
            info.setShopSpecificAddress(shopSpecificAddress);
            info.setCityName(cityName);
            info.setCityCode(cityCode);
            info.setSignPicture(signPicture);
            info.setCompanyName(companyName);
            info.setBusinessLicence(businessLicence);
            info.setDoorPictureLeft(doorPictureLeft);
            info.setDoorPictureRight(doorPictureRight);
            info.setHandPicture(handPicture);
            info.setDevMac(devMacAddress);
            info.setDeviceCode(kMRecordCode);

            if (StringUtils.isBlank(sdkUserId)) {
                log.warn("param sdkUserId is empty");
                return StatusCode.PARAM_ERROR.toJSON("sdkUserId不能为空");
            }
            if (StringUtils.isBlank(appId)) {
                log.warn("param appId is empty");
                return StatusCode.PARAM_ERROR.toJSON("appId不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                log.warn("param phone is empty");
                return StatusCode.PARAM_ERROR.toJSON("phone不能为空");
            }
            // 校验参数
            if (StringUtils.isBlank(info.getDeviceCode())) {
                log.warn("param deviceCode is empty");
                return StatusCode.PARAM_ERROR.toJSON("deviceCode不能为空");
            }
            // 校验参数
            String checkParams = checkParams(info);
            if (StringUtils.isNotBlank(checkParams)) {
                return checkParams;
            }

            SdkAppConfModel confModel = sdkUserDAO.getSdkAppConf(appId);
            if (ObjectUtils.isNull(confModel)) {
                log.warn("DB: getSdkUserMap return null");
                return StatusCode.SYSTEM_EXCEPTION.toJSON("数据异常,请联系管理员。");
            }

            Map<String, String> baseMap = appConfDAO.getConfValuesResMap(OtherConfType.USER_TITLE, confModel.getDetailType());
            if (ObjectUtils.isNullOrEmpty(baseMap)) {
                log.warn("DB: getConfValuesResMap return null,detailType is" + confModel.getDetailType());
                return StatusCode.SYSTEM_EXCEPTION.toJSON("数据异常,请联系管理员。");
            }
            User user = new User();
            user.setSourceType(confModel.getSourceType());
            user.setDetailType(confModel.getDetailType());
            String userId = baseMap.get(OtherConfType.USER_TITLE.getConfName()) + getUserId();
            user.setUserId(userId);
            user.setDealerId(userId);

            // 校验身份证号码、企业营业执照已激活用户数量
            String checkNum = checkIdCardAndBusinessLicence(merchantType, identityCard, user, businessLicence);
            if (StringUtils.isNotBlank(checkNum)) {
                return checkNum;
            }

            // 校验黑名单
            String checkIdCardBlack = checkIdCardIsBlack(identityCard);
            if (StringUtils.isNotBlank(checkIdCardBlack)) {
                return checkIdCardBlack;
            }

            // 校验激活信息
            String checkActivationOrder = checkActivationOrder(sdkUserId, confModel.getDetailType());
            if (StringUtils.isNotBlank(checkActivationOrder)) {
                return checkActivationOrder;
            }

            // TODO：需要确认是否加入以下喜牛电子合同相关
            // 喜牛商户校验电子合同填写商户信息
//            if (user.getSourceType() == Constant.SourceType.XINIU && user.getDetailType() == Constant.DetailType.XINIU) {
//                Map<String, String> allTables = appConfDAO.getAllTables(user.getDetailType());
//                Map<String, String> merchantInfo = userDAO.getBuyModelInfo(user.getMerchantId(), allTables);
//                String sign_pic_url = merchantInfo.get("sign_pic_url");
//                String merch_type = merchantInfo.get("merch_type");
//                String merch_name = merchantInfo.get("merch_name");
//                String buz_code = merchantInfo.get("buz_code");
//
//                String userName = identityCardName.replaceAll("\r|\n", "");
//                String companyNameXn = StringUtils.isBlank(json.getString("companyNameXn")) ? userName
//                        : json.getString("companyNameXn").replaceAll("\r|\n", "");
//                if (!"0".equals(merch_type) && !merchantType.equals(merch_type)) {
//                    log.warn(user.getUserId() + "商户属性和购买时不同；原信息：" + merch_type + ",激活提交信息：" + merchantType
//                            + ",sign_pic_url=" + sign_pic_url);
//                    return StatusCode.SYSTEM_EXCEPTION.toJSON("商户属性和购买时不同。");
//                }
//                if (!StringUtil.isNULL(merch_name) && !companyNameXn.equals(merch_name)) {
//                    log.warn(user.getUserId() + "商户名称和购买时不同;原信息：" + merch_name + ",激活提交信息：" + companyName);
//                    return StatusCode.SYSTEM_EXCEPTION.toJSON("商户名称和购买时不同。");
//                }
//                if (!StringUtil.isNULL(buz_code) && !identityCard.equalsIgnoreCase(buz_code)) {
//                    log.warn(user.getUserId() + "商户证件编号和购买时不同;原信息：" + buz_code + ",激活提交信息：" + identityCard);
//                    return StatusCode.SYSTEM_EXCEPTION.toJSON("商户证件编号和购买时不同。");
//                }
//            }

            SelfRegistering s = new SelfRegistering();
            // 用户填写的设备Id
            DeviceIdInfo deviceInfo = userDAO.getDeviceIdInfo(kMRecordCode);
            // 校验设备号
            String checkDevice = checkDevice(deviceInfo, kMRecordCode, user);
            if (ObjectUtils.nonNull(checkDevice)) {
                return checkDevice;
            }
            if (!devMacAddress.equals(deviceInfo.getMac())) {
                log.warn("mac地址不一致,request macaddress:" + devMacAddress + ",info:" + deviceInfo.toString());
            }

            s.setAppId(appId);
            s.setKMRecordCode(kMRecordCode);
            s.setPopchannel(deviceInfo.getSuper_dealerid());
            s.setDevMacAddress(deviceInfo.getMac());
            s.setPopchannel_name(deviceInfo.getDealer_name());
            // ib_kameng_deliveryrecord中attribute和merchante_attribute定义一致ABCD
            final int isp = deviceInfo.getIsp();
            s.setMerchant_attribute(isp);
            // 新增isp,provinceName绑定设备所属售卡权限及范围,isp,provinceNamec查询到一个scopeId插入商户激活审核表
            final String subStr = deviceInfo.getProvinceName().trim().substring(0, 2);// 取省份名称前两位模糊匹配区域码
            Scope checkScope = webUserDAO.checkScope(isp, subStr);
            if (StringUtil.isNULL(checkScope)) {
                log.warn("submitInfo[参数isp:provinceName错误]" + isp + ":" + deviceInfo.getProvinceName());
                return StatusCode.PARAM_ERROR.toJSON("营运商和区域对应位置编号不存在");
            }
            s.setScopeId(checkScope.getScopeId());

            ModelInfo modelInfo = userDAO.getDealerModel(deviceInfo.getSuper_dealerid());
            if (ObjectUtils.isNull(modelInfo)) {
                log.warn("getDealerModel return null, " + deviceInfo);
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }
            s.setPhoneModel(modelInfo.getPhoneModel());
            s.setDiscountModel(modelInfo.getDiscountModel());
            s.setTransterModel(modelInfo.getIncomeTransterModel());
            s.setDwkModel(modelInfo.getDwkModel());
            s.setPackModel(modelInfo.getPackModel());
            s.setWhiteCardPay(modelInfo.getWhiteCardPay());
            s.setWhiteCardReturn(modelInfo.getWhiteCardReturn());

            // TODO:SDK商户激活目前不存在邀请码相关需求
//            if (StringUtils.isBlank(s.getSuper_dealer_id())) {
//                final String inviteCode = json.getString("inviteCode");// 邀请码
//                Merchant supMerchant = userDAO.getDealerInfoByInviteCode(inviteCode);
//                String supDealerId = "";
//                String supDealerName = "";
//                if (Objects.nonNull(supMerchant)) {
//                    // 是卡盟的商户,邀请码不是卡盟的就提示错误信息
//                    if (user.getSourceType() == Constant.SourceType.KAMENG && supMerchant.getSourceType() != Constant.SourceType.KAMENG) {
//                        log.warn("非卡盟邀请码,userId=" + user.getUserId() + ",inviteCode=" + inviteCode);
//                        return StatusCode.PARAM_ERROR.toJSON("邀请码填写错误,请重新输入");
//                    }
//
//                    supDealerId = supMerchant.getDealerId();
//                    supDealerName = supMerchant.getCompanyName();
//                }
//                s.setSuper_dealer_id(supDealerId);
//                s.setSuper_dealer_name(supDealerName);
//                s.setSupper_invite_code(inviteCode);
//            }

            // 签名合并的图片 使用原图片合并 去掉水印标识
            final String signMergePicture = (signPicture.substring(0, signPicture.lastIndexOf(".")) + "_merge.png")
                    .replace("_narrow", "");
            final long nowTime = Clock.systemDefaultZone().millis();
            String orderId = Constant.MERCHANT_ORDER_REGISTER + DateUtils.format(nowTime, "yyMMddHHmmss") + phone.substring(4);
            s.setModifyTime(nowTime);
            s.setOrderId(orderId);
            s.setMerchantType(Integer.parseInt(merchantType));
            final String userName = identityCardName.replaceAll("\r", "").replaceAll("\n", "");
            s.setUser_name(userName);
            s.setCompany_name(StringUtils.isBlank(companyName) ? userName : companyName.replaceAll("\r", "").replaceAll("\n", ""));
            s.setIdCard(StringUtils.isNotBlank(businessLicence) ? businessLicence : identityCard); // 企业营业执照编号
            s.setCityCode(cityCode);
            s.setCityName(cityName);
            String address = shopAddress.replaceAll("\r", "").replaceAll("\n", "");
            s.setAddress(address);
            s.setImgNo1(doorPictureLeft);
            s.setImgNo2(doorPictureRight);
            s.setImgNo3(handPicture);
            s.setImgNo4(signPicture);
            s.setUser_id(user.getUserId());
            s.setDealer_id(user.getDealerId());
            s.setPhone(phone);
            s.setSignMergePicture(signMergePicture);
            s.setHeadPicture(identifyPhotoHead);
            s.setStoreAddress(shopSpecificAddress);

            // 因为获取不到dealerId,所以获取不到super_dealer_id相关,即不能查询getMerchant()
//            if (ObjectUtils.nonNullOrEmpty(s.getSuper_dealer_id())) {
//                Merchant supSupMem = userDAO.getMerchant(s.getSuper_dealer_id());
//                if (ObjectUtils.nonNull(supSupMem)) {
//                    s.setSuperSuperDealerId(supSupMem.getSuperDealerId());
//                    s.setSuperSuperDealerName(supSupMem.getSuperDealerName());
//                }
//            }

            s.setIsManage(deviceInfo.getIsManager());
            s.setSourceType(user.getSourceType());
            s.setDetailType(user.getDetailType());
            s.setShopAddress(shopAddress);
            s.setShopSpecificAddress(shopSpecificAddress);
            s.setPeriod(period);
            s.setIdentityCard(identityCard);
            s.setIdentityCardName(identityCardName);
            s.setIdentityCardAddress(identityCardAddress);
            s.setIdentifyPhotoHead(identifyPhotoHead);
            s.setIdentifyPhotoFront(identifyPhotoFront);
            s.setIdentifyPhotoReverse(identifyPhotoReverse);
            s.setIdentifyPhotoHand(identifyPhotoHand);
            s.setOperationType("1"); // 操作类型，1：SDK商户激活，其他：空
            s.setSdkUserId(sdkUserId);

            // 创建激活记录
            boolean result = userDAO.addRegistMerchant(s);
            if (!result) {
                log.warn("DB error,addRegistMerchant return " + false);
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }

            // 因为获取不到merchantId,所以不能查询getMerchantDetail()
            // 校验是否有签署过隐私协议
//            MerchantDetailInfo merchantDetail = userDAO.getMerchantDetail(user.getMerchantId());
//            if (Objects.isNull(merchantDetail)) {
//                // 保存隐私协议签署记录
//                boolean bool = userDAO.addMerchantDetail(user.getMerchantId());
//                if (!bool) {
//                    log.warn("DB error,addMerchantDetail return " + false);
//                    return StatusCode.SYSTEM_EXCEPTION.toJSON();
//                }
//            }

            // 封装自动审核相关数据
            RespInfo respInfo = new RespInfo(orderId, "1", merchantType, String.valueOf(s.getMerchant_attribute()), "1",
                    identityCard, identityCardName, identityCardAddress, Constant.ums_url + identifyPhotoFront,
                    Constant.ums_url + identifyPhotoReverse, Constant.ums_url + identifyPhotoHand);
            respInfo.setIdCardPeriod(period);
            respInfo.setHeadImageLocation(Constant.ums_url + identifyPhotoHead);
            respInfo.setOrderType("1"); // 走老流程

            AutomaticAudittask.getInstance().execute(JSONObject.toJSONString(respInfo));
            if (s.getIsManage() == 1) {
                String msg = "审核结果将以业务消息的形式通知，请您注意查收!\r激活成功，您便可以对专营号段进行流转申请操作。";
                return StatusCode.SUCCESS.json().msg(msg).toString();
            }
            return StatusCode.SUCCESS.toJSON();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        } finally {
            sdkUserDAO.redis_del(lockKey);
        }
    }

    private Boolean checkImg(String dir) {
        File f = new File(dir);
        return f.exists();
    }

    private String checkDevice(DeviceIdInfo deviceInfo, String paramDeviceId, User user) {
        if (deviceInfo == null) {
            log.warn("Not found deviceinfo.deviceCode=" + paramDeviceId);
            return StatusCode.ANNO_NOT_FOUND.toJSON("未查到该设备相关信息，请更换其他设备。");
        }
        if (user.getSourceType() == Constant.SourceType.KAMENG) {
            List<String> appDealerIds = appConfDAO.getAll(OtherConfType.MODEL_DEALERIDS);
            if (appDealerIds == null) {
                log.warn("getModelDealerId return null," + null);
                return StatusCode.SYSTEM_EXCEPTION.json().toString();
            }
            if (ObjectUtils.nonNullOrEmpty(deviceInfo.getSuper_dealerid())
                    && appDealerIds.contains(deviceInfo.getSuper_dealerid())) {
                log.warn("喜牛的设备不能用于卡盟绑定," + deviceInfo.toString());
                return StatusCode.ANNO_NOT_FOUND.toJSON("该设备不能用于卡盟平台,请更换其他设备。");
            }
        } else {
            List<String> appDealerIds = appConfDAO.getConfValues(OtherConfType.MODEL_DEALERIDS, user.getDetailType());
            if (appDealerIds == null) {
                log.warn("getModelDealerId return null," + user.getDetailType());
                return StatusCode.SYSTEM_EXCEPTION.json().toString();
            }
            if (ObjectUtils.nonNullOrEmpty(deviceInfo.getSuper_dealerid())
                    && !appDealerIds.contains(deviceInfo.getSuper_dealerid())) {
                log.info("设备不对应," + deviceInfo.toString());
                return StatusCode.ANNO_NOT_FOUND.toJSON("该设备不能用于本平台,请更换其他设备。");
            }
        }

        if (deviceInfo.getIsManager() == 0) {
            if (deviceInfo.getState() == 1) {
                log.warn("设备已被占用,info:" + deviceInfo.toString());
                return StatusCode.SYSTEM_EXCEPTION.toJSON("该设备已被激活,请更换其他设备。");
            }
            if (deviceInfo.getState() == 2) {
                log.warn("设备已被占用,info:" + deviceInfo.toString());
                return StatusCode.SYSTEM_EXCEPTION.toJSON("该设备已被锁定,请更换设备。");
            }
        }
        return null;
    }

    private String checkIdCardIsBlack(String idCard) {
        // 判断身份证黑名单
        final boolean res = blackIdCardDAO.idCardUsed(idCard);
        if (!res) {
            log.error("商户被加入身份证名单tb_black_idcard,idCard=" + idCard);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("身份证异常,请联系管理员");
        }
        return null;
    }

    private String checkParams(MerchantActivateParamsInfo info) {
        if (StringUtils.isBlank(info.getIdentityCard())) {
            log.warn("param identityCard is empty");
            return StatusCode.PARAM_ERROR.toJSON("identityCard不能为空");
        }
        if (StringUtils.isBlank(info.getIdentityCardName())) {
            log.warn("param identityCardName is empty");
            return StatusCode.PARAM_ERROR.toJSON("identityCardName不能为空");
        }
        if (StringUtils.isBlank(info.getIdentityCardAddress())) {
            log.warn("param identityCardAddress is empty");
            return StatusCode.PARAM_ERROR.toJSON("identityCardAddress不能为空");
        }
        if (StringUtils.isBlank(info.getPeriod())) {
            log.warn("param period is empty");
            return StatusCode.PARAM_ERROR.toJSON("period不能为空");
        }
//        if (StringUtils.isBlank(info.getIdentifyPhotoHead())) {
//            log.warn("param identifyPhotoHead is empty");
//            return StatusCode.PARAM_ERROR.toJSON("identifyPhotoHead不能为空");
//        }
        if (StringUtils.isBlank(info.getIdentifyPhotoFront())) {
            log.warn("param identifyPhotoFront is empty");
            return StatusCode.PARAM_ERROR.toJSON("identifyPhotoFront不能为空");
        }
        if (StringUtils.isBlank(info.getIdentifyPhotoReverse())) {
            log.warn("param identifyPhotoReverse is empty");
            return StatusCode.PARAM_ERROR.toJSON("identifyPhotoReverse不能为空");
        }
        if (StringUtils.isBlank(info.getIdentifyPhotoHand())) {
            log.warn("param identifyPhotoHand is empty");
            return StatusCode.PARAM_ERROR.toJSON("identifyPhotoHand不能为空");
        }
        if (StringUtils.isBlank(info.getMerchantType())) {
            log.warn("param merchantType is empty");
            return StatusCode.PARAM_ERROR.toJSON("merchantType不能为空");
        }
        if (StringUtils.isBlank(info.getShopAddress())) {
            log.warn("param shopAddress is empty");
            return StatusCode.PARAM_ERROR.toJSON("shopAddress不能为空");
        }
        if (StringUtils.isBlank(info.getShopSpecificAddress())) {
            log.warn("param shopSpecificAddress is empty");
            return StatusCode.PARAM_ERROR.toJSON("shopSpecificAddress不能为空");
        }
        if (StringUtils.isBlank(info.getCityCode())) {
            log.warn("param cityCode is empty");
            return StatusCode.PARAM_ERROR.toJSON("cityCode不能为空");
        }
        if (StringUtils.isBlank(info.getCityName())) {
            log.warn("param cityName is empty");
            return StatusCode.PARAM_ERROR.toJSON("cityName不能为空");
        }
        if (StringUtils.isBlank(info.getSignPicture())) {
            log.warn("param signPicture is empty");
            return StatusCode.PARAM_ERROR.toJSON("signPicture不能为空");
        }

        // 企业需要判断以下条件
        if ("1".equals(info.getMerchantType())) {
            if (StringUtils.isBlank(info.getCompanyName())) {
                log.warn("param companyName is empty");
                return StatusCode.PARAM_ERROR.toJSON("companyName不能为空");
            }
            if (StringUtils.isBlank(info.getBusinessLicence())) {
                log.warn("param businessLicence is empty");
                return StatusCode.PARAM_ERROR.toJSON("businessLicence不能为空");
            }
            if (StringUtils.isBlank(info.getDoorPictureLeft())) {
                log.warn("param doorPictureLeft is empty");
                return StatusCode.PARAM_ERROR.toJSON("doorPictureLeft不能为空");
            }
            if (StringUtils.isBlank(info.getDoorPictureRight())) {
                log.warn("param doorPictureRight is empty");
                return StatusCode.PARAM_ERROR.toJSON("doorPictureRight不能为空");
            }
            if (StringUtils.isBlank(info.getHandPicture())) {
                log.warn("param handPicture is empty");
                return StatusCode.PARAM_ERROR.toJSON("handPicture不能为空");
            }
        }
        return null;
    }

    @Override
    public String merchantActivationPreAudit(User user, JSONObject json) {
        String operationType = json.getString("operationType"); // 操作类型：1激活，2补录
        String identityCard = json.getString("identityCard");
        String identityCardName = json.getString("identityCardName");
        String identityCardAddress = json.getString("identityCardAddress");
        String period = json.getString("period");
        String kMRecordCode = json.getString("deviceCode");

        if (StringUtils.isBlank(operationType)) {
            log.error("param operationType is null");
            return StatusCode.PARAM_ERROR.toJSON("参数operationType不能为空");
        }
        if (StringUtils.isBlank(identityCard)) {
            log.error("param identityCard is null");
            return StatusCode.PARAM_ERROR.toJSON("参数identityCard不能为空");
        }
        if (StringUtils.isBlank(identityCardName)) {
            log.error("param identityCardName is null");
            return StatusCode.PARAM_ERROR.toJSON("参数identityCardName不能为空");
        }
        if (StringUtils.isBlank(identityCardAddress)) {
            log.error("param identityCardAddress is null");
            return StatusCode.PARAM_ERROR.toJSON("参数identityCardAddress不能为空");
        }
        if (StringUtils.isBlank(period)) {
            log.error("param period is null");
            return StatusCode.PARAM_ERROR.toJSON("参数period不能为空");
        }
        if (StringUtils.isBlank(kMRecordCode)) {
            log.error("param deviceCode is null");
            return StatusCode.PARAM_ERROR.toJSON("参数deviceCode不能为空");
        }

        DeviceIdInfo deviceInfo = userDAO.getDeviceIdInfo(kMRecordCode);
        if (Objects.isNull(deviceInfo)) {
            log.error("DB is error,getDeviceIdInfo is null");
            return StatusCode.SYSTEM_EXCEPTION.toJSON("系统异常，请稍后再试。");
        }

        // SDK商户激活需要加入redis预审身份证文字信息(ams)
        SdkActivationPreAuditInfo info = new SdkActivationPreAuditInfo();
        info.setIdentityCard(identityCard);
        info.setIdentityCardName(identityCardName);
        info.setIdentityCardAddress(identityCardAddress);
        info.setPeriod(period);
        info.setSourceType(user.getSourceType());
        info.setIsp(String.valueOf(deviceInfo.getIsp()));
        info.setPapersType(SystemConstant.PAPERSTYPE_IDCARD);
        info.setOperationType(operationType);
        final String infoStr = JSONObject.toJSONString(info);
        Long result = sdkUserDAO.redis_rpush(RedisConstant.MERCHANT_ACTIVATION_AUDITED_KEY, infoStr);
        if (result == null) {
            log.error("redis连接异常");
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
        log.info("SDK商户激活预审： Redis(AMS) KEY:" + RedisConstant.MERCHANT_ACTIVATION_AUDITED_KEY + ",val:" + infoStr);

        return StatusCode.SUCCESS.toJSON();
    }

    @Override
    public String preAuditBack(User user, JSONObject json) {
        JSONObject jsonObject = new JSONObject();
        String operationType = json.getString("operationType"); // 操作类型：1激活，2补录
        String idCard = json.getString("identityCard");
        if (StringUtils.isBlank(idCard)) {
            log.error("param identityCard is null");
            return StatusCode.PARAM_ERROR.toJSON("参数identityCard不能为空");
        }
        if (StringUtils.isBlank(operationType)) {
            log.error("param operationType is null");
            return StatusCode.PARAM_ERROR.toJSON("参数operationType不能为空");
        }

        ActivationPreAuditLogModel model = sdkUserDAO.getPreAuditLog(idCard, operationType);
        if (Objects.isNull(model)) {
            log.error("DB not find data,idCard is " + idCard);
            jsonObject.put("result", 0);
        }
        jsonObject.put("result", model.getResult());
        jsonObject.put("desc", model.getDesc());

        return StatusCode.SUCCESS.toDiyJson("data", jsonObject);
    }

    @Override
    public String saveMerchantFill(User user, JSONObject json) {
        String identityCard = json.getString("identityCard"); // 企业和个人都是身份证号码
        String identityCardName = json.getString("identityCardName");
        String identityCardAddress = json.getString("identityCardAddress");
        String period = json.getString("period");
        String merchantType = json.getString("merchantType");
        String shopAddress = json.getString("shopAddress");
        String shopSpecificAddress = json.getString("shopSpecificAddress");
        String identifyPhotoHand = json.getString("identifyPhotoHand");
        String identifyPhotoHead = json.getString("identifyPhotoHead");
        String identifyPhotoFront = json.getString("identifyPhotoFront");
        String identifyPhotoReverse = json.getString("identifyPhotoReverse");
        String companyName = json.getString("companyName");
        String signPicture = json.getString("signPicture");
        String businessLicence = json.getString("businessLicence"); // 营业执照编号，个人用户不用传
        String doorPictureLeft = json.getString("doorPictureLeft");
        String doorPictureRight = json.getString("doorPictureRight");
        String handPicture = json.getString("handPicture");
        String cityName = json.getString("cityName");
        String cityCode = json.getString("cityCode");
        String devMacAddress = "";
        if (json.containsKey("devMac")) {
            devMacAddress = json.getString("devMac");
        }

        MerchantActivateParamsInfo info = new MerchantActivateParamsInfo();
        info.setDevMac(devMacAddress);
        info.setIdentityCard(identityCard);
        info.setIdentityCardName(identityCardName);
        info.setIdentityCardAddress(identityCardAddress);
        info.setPeriod(period);
        info.setShopAddress(shopAddress);
        info.setShopSpecificAddress(shopSpecificAddress);
        info.setIdentifyPhotoHead(identifyPhotoHead);
        info.setIdentifyPhotoFront(identifyPhotoFront);
        info.setIdentifyPhotoReverse(identifyPhotoReverse);
        info.setIdentifyPhotoHand(identifyPhotoHand);
        info.setMerchantType(merchantType);
        info.setSignPicture(signPicture);
        info.setCompanyName(companyName);
        info.setBusinessLicence(businessLicence);
        info.setDoorPictureLeft(doorPictureLeft);
        info.setDoorPictureRight(doorPictureRight);
        info.setHandPicture(handPicture);
        info.setCityName(cityName);
        info.setCityCode(cityCode);

        // 校验参数
        String checkParams = checkParams(info);
        if (StringUtils.isNotBlank(checkParams)) {
            return checkParams;
        }

        String merchantId = user.getMerchantId();
        MerchantInfoFill infoFillDB = merchantFillServiceDAO.getLast(merchantId);
        if (Objects.isNull(infoFillDB) || Objects.isNull(infoFillDB.getOrderId())) {
            log.error("DB数据异常,getLast is null,merchantId=" + merchantId);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("数据异常,请联系管理员");
        }

        Merchant merchant = merchantDAO.getByMerchantId(merchantId);
        if (Objects.isNull(merchant)) {
            log.error("DB连接异常");
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
        int userType = merchant.getUserTypeId();
        String nickName = merchantDAO.getUserTypeNickName(userType);
        final String YYMMddHHmmss = DateUtils.format("YYMMddHHmmss");
        final String orderId = Constant.MERCHANT_ORDER_PREFIX + YYMMddHHmmss + StringUtil.randomNumberString(4);

        MerchantInfoFill infoFill = new MerchantInfoFill();
        infoFill.setUserName(identityCardName);
        infoFill.setIdentifyPhotoFront(identifyPhotoFront);
        infoFill.setIdentifyPhotoReverse(identifyPhotoReverse);
        infoFill.setIdentifyPhotoHand(identifyPhotoHand);
        infoFill.setCityCode(cityCode);
        infoFill.setCityName(cityName);
        infoFill.setBusinessLicence(StringUtils.isNotBlank(businessLicence) ? businessLicence : identityCard);
        infoFill.setShopAddress(shopAddress);
        infoFill.setShopSpecificAddress(shopSpecificAddress);
        infoFill.setAddress(shopAddress);
        infoFill.setStoreAddress(shopSpecificAddress);
        infoFill.setOrderId(orderId);
        infoFill.setRegistOrderId(infoFillDB.getOrderId());
        infoFill.setCreateTime(System.currentTimeMillis());
        infoFill.setUserId(user.getUserId());
        infoFill.setDealerId(infoFillDB.getDealerId());
        infoFill.setMerchantType(infoFillDB.getMerchantType());
        if (infoFillDB.getMerchantType() == 2) {
            infoFill.setCompanyName(identityCardName);
        } else {
            infoFill.setCompanyName(companyName);
        }
        infoFill.setOrderStatus(Constant.RegisterAuditOrderStatus.WAIT_AUDIT);
        infoFill.setMerchantId(user.getMerchantId());

        // 图片兼容变成网路径
        String left = "", right = "", hand = "", head = "", signPicture1 = "";
        if (StringUtils.isNotBlank(doorPictureRight)) {
            right = (doorPictureRight.substring(0, doorPictureRight.lastIndexOf("."))) + ".png";
            if (right.contains("http")) {
                right = ((right.substring(right.lastIndexOf("com"), right.lastIndexOf("."))) + ".png").substring(3);
            }
        }
        if (StringUtils.isNotBlank(identifyPhotoHead)) {
            head = (identifyPhotoHead.substring(0, identifyPhotoHead.lastIndexOf("."))) + ".png";
            if (head.contains("http")) {
                head = ((head.substring(head.lastIndexOf("com"), head.lastIndexOf("."))) + ".png").substring(3);
            }
        }
        if (StringUtils.isNotBlank(doorPictureLeft)) {
            left = (doorPictureLeft.substring(0, doorPictureLeft.lastIndexOf("."))) + ".png";
            if (left.contains("http")) {
                left = ((left.substring(left.lastIndexOf("com"), left.lastIndexOf("."))) + ".png").substring(3);
            }
        }
        if (StringUtils.isNotBlank(handPicture)) {
            hand = (handPicture.substring(0, handPicture.lastIndexOf("."))) + ".png";
            if (hand.contains("http")) {
                hand = ((hand.substring(hand.lastIndexOf("com"), hand.lastIndexOf("."))) + ".png").substring(3);
            }
        }
        if (StringUtils.isNotBlank(signPicture)) {
            signPicture1 = (signPicture.substring(0, signPicture.lastIndexOf("."))) + ".png";
            if (signPicture1.contains("http")) {
                signPicture1 = ((signPicture1.substring(signPicture1.lastIndexOf("com"), signPicture1.lastIndexOf("."))) + ".png").substring(3);
            }
        }

        infoFill.setHeadPicture(head);
        infoFill.setSignPicture(signPicture1);
        infoFill.setDoorPictureLeft(left);
        infoFill.setDoorPictureRight(right);
        infoFill.setHandPicture(hand);
        infoFill.setPeriod(trimNULL(infoFillDB.getPeriod()));
        infoFill.setSourceType(infoFillDB.getSourceType());
        infoFill.setRequestPhone(infoFillDB.getRequestPhone());
        infoFill.setAuditType(1);// 1 实时审核 2 事后审核 3 自动审核
        infoFill.setCustomer("");
        infoFill.setAutoAuditDesc("");
        infoFill.setGztCheck("");
        infoFill.setRemarks("");
        infoFill.setNickName(nickName);
        if (1 == infoFillDB.getMerchantType()) {
            if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoFront())) {
                identifyPhotoFront = (infoFill.getIdentifyPhotoFront().substring(0,
                        infoFill.getIdentifyPhotoFront().lastIndexOf("."))) + ".png";
                if (identifyPhotoFront.contains("http")) {
                    identifyPhotoFront = ((identifyPhotoFront.substring(identifyPhotoFront.lastIndexOf("com"),
                            identifyPhotoFront.lastIndexOf("."))) + ".png").substring(3);
                }
                infoFill.setIdentifyPhotoFront(identifyPhotoFront);
            }
            if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoReverse())) {
                identifyPhotoReverse = (infoFill.getIdentifyPhotoReverse().substring(0,
                        infoFill.getIdentifyPhotoReverse().lastIndexOf("."))) + ".png";
                if (identifyPhotoReverse.contains("http")) {
                    identifyPhotoReverse = ((identifyPhotoReverse.substring(identifyPhotoReverse.lastIndexOf("com"),
                            identifyPhotoReverse.lastIndexOf("."))) + ".png").substring(3);
                }
                infoFill.setIdentifyPhotoReverse(identifyPhotoReverse);
            }
            if (StringUtils.isNotBlank(infoFill.getIdentifyPhotoHand())) {
                identifyPhotoHand = (infoFill.getIdentifyPhotoHand().substring(0,
                        infoFill.getIdentifyPhotoHand().lastIndexOf("."))) + ".png";
                if (identifyPhotoHand.contains("http")) {
                    identifyPhotoHand = ((identifyPhotoHand.substring(identifyPhotoHand.lastIndexOf("com"),
                            identifyPhotoHand.lastIndexOf("."))) + ".png").substring(3);
                }
                infoFill.setIdentifyPhotoHand(identifyPhotoHand);
            }
        } else {
            infoFill.setIdentifyPhotoFront(identifyPhotoFront);
            infoFill.setIdentifyPhotoReverse(identifyPhotoReverse);
            infoFill.setIdentifyPhotoHand(identifyPhotoHand);
        }

        int index = signPicture.lastIndexOf("/");
        final String fileName = signPicture.substring(index + 1);
        String signMergePicture = signPicture.substring(0, index + 1) + fileName.replace(".", "_merge.");
        signMergePicture = signMergePicture.replace("_narrow", "");
        infoFill.setSignMergePicture(signMergePicture);

        AutoAuditEntity autoAudit = new AutoAuditEntity();
        autoAudit.setBackImageLocation(infoFill.getDoorPictureRight());
        autoAudit.setFrontImageLocation(infoFill.getDoorPictureLeft());
        autoAudit.setHandImageLocation(infoFill.getHandPicture());
        autoAudit.setHeadImageLocation(infoFill.getHeadPicture());
        autoAudit.setIdCardAddress(infoFill.getAddress());
        autoAudit.setIdCardName(infoFill.getUserName());
        autoAudit.setIdCardNo(infoFill.getBusinessLicence());
        autoAudit.setIdCardPeriod(infoFill.getPeriod());
        autoAudit.setIsp("1");
        autoAudit.setMerchantType(infoFill.getMerchantType());
        autoAudit.setOpenModel("3");// 相册、拍照
        autoAudit.setOrderId(orderId);
        autoAudit.setSource("1");

        final String auditStr = JSONObject.toJSONString(autoAudit);

        // 个人、企业都需要加入redis自动审核
        Long result = merchantFillServiceDAO.redis_rpush(RedisConstant.AUDIT_KEY, auditStr);
        if (result == null) {
            log.error("redis连接异常");
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
        boolean bool = merchantFillServiceDAO.insert(infoFill);
        if (!bool) {
            log.error("数据库异常");
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }

        return StatusCode.SUCCESS.toJSON();

    }

    private String trimNULL(String str) {
        if (str == null) {
            return "";
        }
        return str.trim();
    }

    @Override
    public String checkNumByBusinessLicence(User user, JSONObject json) {
        String businessLicence = json.getString("businessLicence"); // 营业执照编号，个人用户不用传
        if (StringUtils.isBlank(businessLicence)) {
            log.warn("param businessLicence is empty");
            return StatusCode.PARAM_ERROR.toJSON("businessLicence不能为空");
        }
        String checkBusinessLicence = checkBusinessLicence(businessLicence, user);
        if (StringUtils.isNotBlank(checkBusinessLicence)) {
            return checkBusinessLicence;
        }

        return StatusCode.SUCCESS.toJSON();
    }

    private String checkActivationOrder(String sdkUserId, Integer detailType) {
        SdkUserMapModel model = sdkUserDAO.getSdkUserMap(sdkUserId);
        if (ObjectUtils.nonNull(model)) {
            log.warn("DB: getSdkUserMap return not null");
            return StatusCode.SYSTEM_EXCEPTION.toJSON("你已激活,可以进行开卡操作。");
        }

        List<RegistOrderInfo> infoList = registOrderInfoDAO.getRegistorAuditListByUserId(sdkUserId, detailType);
        if (ObjectUtils.nonNull(infoList) && infoList.size() > 0) {
            log.warn("DB: getRegistorAuditListByUserId return not null, sdkUserId为" + sdkUserId);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("您的激活申请正在审核中,请不要重复提交。");
        }

        return "";
    }

    @Override
    public String getActivationOrderStatus(UserToken userToken, HeaderEntity authHeader) {
        String sdkUserId = authHeader.getUserId(); // 单点结算userId
        String appId = userToken.getAppId(); // sdk 下家appid

        if (StringUtils.isBlank(sdkUserId)) {
            log.warn("param sdkUserId is empty");
            return StatusCode.PARAM_ERROR.toJSON("sdkUserId不能为空");
        }
        if (StringUtils.isBlank(appId)) {
            log.warn("param appId is empty");
            return StatusCode.PARAM_ERROR.toJSON("appId不能为空");
        }

        SdkAppConfModel confModel = sdkUserDAO.getSdkAppConf(appId);
        if (ObjectUtils.isNull(confModel)) {
            log.warn("DB: getSdkUserMap return null");
            return StatusCode.SYSTEM_EXCEPTION.toJSON("数据异常,请联系管理员。");
        }
        String result = checkActivationOrder(sdkUserId, confModel.getDetailType());
        if (StringUtils.isNotBlank(result)) {
            return result;
        }

        return StatusCode.SUCCESS.toJSON();
    }

}